var app = getApp()
var qqmapsdk = require('../../utils/qqmap');
Page({
    onShareAppMessage() {
        return {
            title: 'swiper',
            path: 'page/component/pages/swiper/swiper'
        }

    },


    data: {
        banners: [],
        dog_detail: [],
        food: [],
        toy: [],
        medicine: [],
        indicatorDots: true,
        vertical: true,
        autoplay: true,
        interval: 4000,
        duration: 500,
        navbar: ['食物', '萌宠', '玩具', '药品'],
        currentTab: 0,   /*初始显示的页面*/
        query: {
            key: ''
        },
        total: [],
        pageNum: 1,
        loading: '数据加载中...',
        goodInfo: {},
        //定位城市信息
        province: "",
        city: "",
        city_code: ""
    },

    getUserLocation() {
        let that = this
        //获取用户的当前设置。返回值中只会出现小程序已经向用户请求过的权限
        wx.getSetting({
            success(res) {
                //console.log(res)
                //scope.userLocation 就是地理授权的标志：
                //res.authSetting['scope.userLocation'] == undefined 表示初始进入该页面
                //res.authSetting['scope.userLocation'] == false 表示非初始化进入该页面 且未授权
                //res.authSetting['scope.userLocation'] == true 表示地理位置授权
                if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
                    //表示非初始化进入该页面 且未授权：
                    wx.showModal({
                        title: '请求授权当前位置',
                        content: '需要获取您的地理位置，请确认授权',
                        showCancel: true,
                        cancelText: '取消',
                        cancelColor: '#000000',
                        confirmText: '确定',
                        confirmColor: '#3CC51F',
                        success: (result) => {
                            if (res.cancel) {
                                wx.showToast({
                                    title: '拒绝授权',
                                    icon: 'none',
                                    duration: 1000
                                });
                            } else if (result.confirm) {
                                //调起客户端小程序设置界面，返回用户设置的操作结果。 
                                //设置界面只会出现小程序已经向用户请求过的权限
                                wx.openSetting({
                                    success: (dataAu) => {
                                        if (dataAu.authSetting["scope.userLocation"] == true) {
                                            wx.showToast({
                                                title: '授权成功',
                                                icon: 'success',
                                                duration: 1000
                                            });
                                            //再次授权之后，调用wx.getLocation的API
                                            that.getLocation()
                                        } else {
                                            wx.showToast({
                                                title: '授权失败',
                                                icon: 'none',
                                                duration: 1000
                                            });
                                        }
                                    }
                                });

                            }
                        }
                    });

                } else if (res.authSetting['scope.userLocation'] == undefined) {
                    //调用wx.getLocation的API
                    that.getLocation()
                } else {
                    //调用wx.getLocation的API
                    that.getLocation()
                }
            }

        })
    },
    /**
     * 获取当前位置坐标经纬度
         步骤2：微信的getLocation接口，获取当前用户的地理位置（微信返回的是经纬度、速度等参数）
     */
    getLocation() {
        let that = this
        //1.获取当前位置坐标经纬度
        wx.getLocation({
            type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
            success: function (res) {
                // success
                //console.log(res)
                var latitude = res.latitude //维度
                var longitude = res.longitude //经度
                //2.根据经纬度获取对应城市信息(使用腾讯位置服务)
                that.getLocal(latitude, longitude)
            },
            fail: function () {
                // fail
            },
            complete: function () {
                // complete
            }
        })
    },
    //步骤3：获取当前地理位置
    getLocal: function (latitude, longitude) {
        let that = this
        //逆地址解析
        qqmapsdk.reverseGeocoder({
            location: {
                latitude: latitude,
                longitude: longitude
            },
            success: function (res) {
                // console.log(res)
                let first_enter = wx.getStorageSync('first_enter')
                wx.setStorageSync('first_enter', false)
                let province = res.result.ad_info.province;
                let city = res.result.ad_info.city;
                let cityCode = res.result.ad_info.city_code;
                let nationCode = res.result.ad_info.nation_code;
                let city_code = cityCode.substring(nationCode.length)
                //如果本地存储没有城市信息，则将定位的城市信息存入本地存储
                if (!wx.getStorageSync('city_code')) {
                    that.setData({
                        city: city,
                        city_code: city_code
                    })
                    wx.setStorageSync('city', city)
                    wx.setStorageSync('city_code', city_code)
                }
                //首次进入，判断定位的城市与本地存储城市信息是否一致；若不一致，则提示是否切换城市信息
                if (first_enter) {
                    if (city_code != wx.getStorageSync('city_code')) {
                        wx.showModal({
                            title: '提示',
                            content: '检测到当前城市为' + city + "，是否切换？",
                            showCancel: true,
                            cancelText: '取消',
                            cancelColor: '#000000',
                            confirmText: '确定',
                            confirmColor: '#3CC51F',
                            success: (result) => {
                                if (result.confirm) {
                                    that.setData({
                                        city: city,
                                        city_code: city_code
                                    })
                                    wx.setStorageSync('city', city)
                                    wx.setStorageSync('city_code', city_code)
                                }
                            }
                        });

                    }
                }
            },
            fail: function (res) {
                //console.log(res)
            }
        })
    },

    //搜索关键字
    inputKey(e) {
        this.data.query.key = e.detail.value
    },
    //重新加载
    refresh(next) {
        this.getList(next)
    },

    //出门指南
    weather() {
        wx.navigateTo({
            url: '/pages/weather/weather',
        })
    },

    //导航栏
    navbarTap: function (e) {
        this.setData({
            currentTab: e.currentTarget.dataset.idx
        })
    },

    //领养寄养信息
    care_list() {
        wx.navigateTo({
            url: '/pages/care_list/care_list',
        })
    },

    // 获取轮播图(封装)
    getbanners() {
        return new Promise((resolve, reject) => {
            wx.get('http://localhost:8000/wx/index/banners').then((res) => {
                this.setData({
                    banners: res
                })
                resolve()
            })

        })
    },


    //获取宠物分页区域(封装)
    getdog_detail: function (next) {
        return new Promise((resolve, reject) => {
            this.setData({ loading: '数据加载中...' })
            wx.get('http://localhost:8000/wx/index/dog_detail?pageNum=', {
                pageNum: this.data.pageNum
            }).then((res) => {
                this.setData({
                    loading: '已经到底了哦~',
                    dog_detail: this.data.dog_detail.concat(res.rows),
                    total: res.total
                })
                resolve()
            }
            )
        })
    },

    //获取食物分页(封装)
    getfood: function (next) {
        return new Promise((resolve, reject) => {
            this.setData({ loading: '数据加载中...' })
            wx.get('http://localhost:8000/wx/index/food?pageNum=', {
                pageNum: this.data.pageNum
            }).then((res) => {
                this.setData({
                    loading: '已经到底了哦~',
                    food: this.data.food.concat(res.rows),
                    total: res.total
                })
                resolve()
            }
            )
        })
    },

    //获取玩具分页(封装)
    gettoy: function (next) {
        return new Promise((resolve, reject) => {
            this.setData({ loading: '数据加载中...' })
            wx.get('http://localhost:8000/wx/index/toy?pageNum=', {
                pageNum: this.data.pageNum
            }).then((res) => {
                this.setData({
                    loading: '已经到底了哦~',
                    toy: this.data.toy.concat(res.rows),
                    total: res.total
                })
                resolve()
            }
            )
        })
    },

    //获取药品分页(封装)
    getmedicine: function (next) {
        return new Promise((resolve, reject) => {
            this.setData({ loading: '数据加载中...' })
            wx.get('http://localhost:8000/wx/index/medicine?pageNum=', {
                pageNum: this.data.pageNum
            }).then((res) => {
                this.setData({
                    loading: '已经到底了哦~',
                    medicine: this.data.medicine.concat(res.rows),
                    total: res.total
                })
                resolve()
            }
            )
        })
    },

    getList() {
        Promise.all([this.getbanners(), this.getdog_detail(), this.getfood(), this.gettoy(),this.getmedicine()]).then(() => {
        }).catch(e => {
        })
    },

    //根据id跳转页面
    Detail(e) {
        var id = e.currentTarget.dataset.id;
        // if ($id){
        wx.navigateTo({
            url: '/pages/details/details?id=' + e.currentTarget.dataset.id + '&type=' + this.data.currentTab
        })
        // }
    },
        ///点击加入购物车
        haveShopping(e){
            if (wx.getStorageSync('userInfo').nickName){
                wx.post('http://localhost:8000/wx/shopping', {
                    memberId:wx.getStorageSync('userInfo')._id,
                    shoppingId:e.currentTarget.dataset.item.id,
                    shoppingType:e.currentTarget.dataset.item.shoppingType
                }).then((res) => {
                    if(res.code = 200){
                        wx.showToast({
                            title: '已加入购物车',
                            icon:'success',
                            //防止一直点击
                            mask:true
                          })
                    } else {
                        wx.showToast({
                            title: '加入购物车失败',
                            icon:'error',
                            //防止一直点击
                            mask:true
                          })
                    }
                })
            } else {
                wx.showModal({
                    title: '温馨提示',
                    content: '请先进行登录',
                    showCancel:false
                })
            }
          
        },
    

    /**
     * 生命周期函数--监听页面加载
     */

    onLoad: function (options) {
        wx.showShareMenu({
            menus: ['shareAppMessage', 'shareTimeline'],
            success(res) {
              console.log(res)
            },
            fail(e) {
              console.log(e)
            }
          })
          this.setData({
            'query.key': options.key || '',
        })
        this.getList()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        var that = this
        if (wx.getStorageSync('city_code')) {
            that.setData({
                city_code: wx.getStorageSync('city_code')
            })
        }
        if (wx.getStorageSync('city')) {
            that.setData({
                city: wx.getStorageSync('city')
            })
        }
        that.getUserLocation()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.data.pageNum = 1
        this.data.dog_detail = []
        this.data.food = []
        this.data.toy = []
        this.data.medicine = []
        this.getList()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        if (this.data.total > this.data.dog_detail.length) {
            this.data.pageNum++
            this.getList()
        }
        if (this.data.total > this.data.food.length) {
            this.data.pageNum++
            this.getList()
        }
        if (this.data.total > this.data.toy.length) {
            this.data.pageNum++
            this.getList()
        }
        if (this.data.total > this.data.medicine.length) {
            this.data.pageNum++
            this.getList()
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
    //     if (res.from === 'button') {
    //         // 来自页面内转发按钮
    //           console.log(res.target)
    //       }
    //       return {
    //           title: 'super分享给好友',
    //           path: '/page/user?id=123',
    //           imageUrl: 'https://img0.baidu.com/it/u=3971760134,427479911&fm=26&fmt=auto&gp=0.jpg'
    //       }
    //   },
    //   // 分享至朋友圈
    //   onShareTimeline: function (res) {
    //       if (res.from === 'button') {
    //         // 来自页面内转发按钮
    //           console.log(res.target)
    //       }
    //       return {
    //           title: 'super分享至朋友圈',
    //           query: 'id=123',
    //           imageUrl: 'https://img0.baidu.com/it/u=3971760134,427479911&fm=26&fmt=auto&gp=0.jpg'
    //       }
    }
})